package dao

import (
	"bilibi.com/comment/model"
	"context"

	"github.com/pkg/errors"
)

func (d *Dao) AddComment(c context.Context, arg *model.AddComment) error {
	return d.db.Table("comment").Create(arg).Error
}

func (d *Dao) CommentQuery(c context.Context, arg *model.ArgQueryComment) (res []*model.Comment, err error) {
	q := d.db.Table("comment")
	if arg.HubuserId > 0 {
		q = q.Where("hubuser_id = ?", arg.HubuserId)
	}
	if arg.ActId > 0 {
		q = q.Where("act_id = ?", arg.ActId)
	}
	if arg.Top > -1 {
		q = q.Where("top = ?", arg.Top)
	}
	if err = q.Order("id desc").Find(&res).Error; err != nil {
		if q.RecordNotFound() {
			err = nil
			return
		}
		err = errors.Wrapf(err, "comments list")
		return
	}
	return
}

func (d *Dao) CommentList(c context.Context, arg *model.ArgList) (res *model.CommentPagination, err error) {
	var items []*model.Comment
	var count int

	q := d.db.Table("comment")
	if err = q.Count(&count).Error; err != nil {
		return
	}
	if err = q.Offset((arg.Pn - 1) * arg.Ps).Limit(arg.Ps).Find(&items).Error; err != nil {
		return
	}
	res = &model.CommentPagination{
		Comments: items,
		Page: model.Page{
			Total: count,
			Pn:    arg.Pn,
			Ps:    arg.Ps},
	}
	return
}

func (d *Dao) Comment(c context.Context, id int64) (res *model.Comment, err error) {
	res = new(model.Comment)
	q := d.db.Table("comment").Where("id=?", id).First(res)
	if q.Error != nil {
		if q.RecordNotFound() {
			err = nil
			res = nil
			return
		}
		err = errors.Wrapf(err, "comment by id")
	}
	return
}

func (d *Dao) UpdateComment(c context.Context, req *model.UpdateComment) error {
	args := map[string]interface{}{}

	if req.Top > -1 {
		args["top"] = req.Top
	}
	if req.Message != "" {
		args["message"] = req.Message
	}
	if req.Name != "" {
		args["name"] = req.Name
	}
	return d.db.Table("comment").Where("id=?", req.ID).Update(args).Error
}

func (d *Dao) DeleteComment(c context.Context, id int64) error {
	return d.db.Table("comment").Where("id=?", id).Delete(&model.Comment{}).Error
}
